package cn.com.egova.permission;

import android.Manifest;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class BasicMethodActivity extends Activity {
    private static final String TAG = "BasicMethodActivity";
    private static final int PERMISSION_REQUESTCODE = 1;
    private Button btn_call;
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic);

        initData();

        initActionBar();

        initView();
    }

    private void initData() {
        title = getIntent().getStringExtra("title");
        if(TextUtils.isEmpty(title)){
            title = "Permission";
        }
    }

    private void initActionBar() {
        ActionBar actionBar = getActionBar();
        if(actionBar!=null){
            actionBar.setTitle(title);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowHomeEnabled(false);
        }
    }

    private void initView() {
        btn_call = (Button) findViewById(R.id.btn_call);
        btn_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){  //23,Android 6.0
//                permission();
//                permission2();
                    permission3();
                }else{
                    call();
                }
            }
        });
    }

    /**
     * 动态申请权限
     * 前台具体表现是:弹出1个对话框,
     */
    private void permission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            //1.没有授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_REQUESTCODE);
            Log.w(TAG,"Android 6.0动态申请首选");
        }else{
            //2.已经授权
            call();
        }
    }


    /**
     * 动态申请权限方式2---增加了(第一次点"禁止",第二次使用该功能时,弹出对话框引导跳转到settings界面的)逻辑.
     */
    private void permission2(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            //1.没有授权
            if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)){
                //1.1弹出"设置"引导对话框
                //当拒绝了授权后,为提升用户体验,可以以弹窗的方式引导用户到设置中去进行设置.
                new AlertDialog.Builder(BasicMethodActivity.this)
                        .setMessage("需要开启权限才能使用此功能")
                        .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //引导用户到设置中去进行设置
                                Intent intent = new Intent();
                                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                intent.setData(Uri.fromParts("package", getPackageName(), null));
                                startActivity(intent);

                            }
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
            }else{
                //1.2不弹出"设置"引导对话框
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, PERMISSION_REQUESTCODE);
            }
        }else{
            //2.已经授权
            call();
        }
    }


    /**
     * 多个权限动态申请的处理:
     * 1.先创建1个集合将所有需要申请的权限存起来;
     * 2.调用requestPermissions方法一次全部申请;
     */
    private void permission3(){
        List<String> permissionLists = new ArrayList<String>();
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.CALL_PHONE);
        }
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
            permissionLists.add(Manifest.permission.CAMERA);
        }

        if(!permissionLists.isEmpty()){//说明肯定有拒绝的权限
            ActivityCompat.requestPermissions(this, permissionLists.toArray(new String[permissionLists.size()]), PERMISSION_REQUESTCODE);
        }else{
            Toast.makeText(this, "权限都授权了，可以搞事情了", Toast.LENGTH_SHORT).show();
        }
    }


    private void call(){
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri uri = Uri.parse("tel:" + "10086");
            intent.setData(uri);
            startActivity(intent);
            Toast.makeText(this,"打电话啦",Toast.LENGTH_SHORT).show();
        }catch (SecurityException e){
            e.printStackTrace();
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }else{
            return super.onOptionsItemSelected(item);
        }
    }


    //单个权限
//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch (requestCode){
//            case PERMISSION_REQUESTCODE:
//                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//                    //用户点击了同意授权
//                    call();
//                }else{
//                    //用户拒绝了授权
//                    Toast.makeText(this,"权限被拒绝",Toast.LENGTH_SHORT).show();
//                }
//                break;
//            default:
//                break;
//        }
//    }


    //多个权限
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case PERMISSION_REQUESTCODE:
                if(grantResults.length > 0){
                    for(int grantResult : grantResults){
                        if(grantResult != PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this, "某一个权限被拒绝了", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }

                    call();
                }
                break;
            default:
                break;
        }
    }
}
